package com.tuanzi.loan.web.bean.settlement;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tuanzi.loan.business.entity.CurrentUser;
import com.tuanzi.loan.business.entity.settlement.CompanyInfo;
import com.tuanzi.loan.business.entity.settlement.ProductLinkInfo;
import com.tuanzi.loan.business.entity.settlement.QualificationInfo;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.entity.system.SystemUser;
import com.tuanzi.loan.business.service.settlement.CompanyInfoService;
import com.tuanzi.loan.business.service.settlement.ProductLinkInfoService;
import com.tuanzi.loan.business.service.settlement.QualificationInfoService;
import com.tuanzi.loan.business.service.system.RoleService;
import com.tuanzi.loan.business.service.system.SystemUserService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.exception.SystemException;
import com.tuanzi.loan.core.util.SpringContextHolder;
import com.tuanzi.loan.vo.view.settlement.CompanyInfoView;
import com.tuanzi.loan.web.configuration.JSFWorkflowBean;
import com.tuanzi.loan.workflow.schedule.SettlementDataBackScheduler;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.*;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

/**
 * @author caiwanlin
 * @create 2018-01-29 10:03
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class CompanyInfoAuditBean extends JSFWorkflowBean<CompanyInfoView> {

	@Override
	public void onSave() {
		if ($.getAuditStatus() == AuditStatus.NO_CHECK.getIndex()) {
			try {
				checkBaseMessage($);
				checkQualificationInfoList($, qualificationInfoList);
			} catch (Exception e) {
				throw new RuntimeException(e.getMessage());
			}
			companyInfoService.saveCompanyInfo($, qualificationInfoList, productLinkInfoList);
		}
	}

	@Override
	public void validate() {

	}

	private final static String PROCESS_DEF_KEY = "CreateFirstParty";

	private StreamedContent businessLicenseFile;
	private String productLink;
	private String remark;

	private List<QualificationInfo> qualificationInfoList;

	private List<ProductLinkInfo> productLinkInfoList;

	private List<SystemUser> principalList;

	private List<SystemUser> auditorList;

	@Autowired
	private CompanyInfoService companyInfoService;

	@Autowired
	private QualificationInfoService qualificationInfoService;

	@Autowired
	private ProductLinkInfoService productLinkInfoService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private SystemUserService systemUserService;

	@PostConstruct
	private void init() {
//		SpringContextHolder.getBean(SettlementDataBackScheduler.class).beginWorkFlowByAccount(companyInfoService.findOne(69L));
		String companyId = getParamFromRequest("id");
		if (companyId == null && task == null) {
			$ = new CompanyInfoView();
			productLinkInfoList = new ArrayList<>();
			productLinkInfoList.add(new ProductLinkInfo());
			qualificationInfoList = new ArrayList<>();
			for (int i = 1; i <= 6; i++) {
				QualificationInfo qualificationInfo = new QualificationInfo();
				qualificationInfo.setAttachmentType(i);
				qualificationInfoList.add(qualificationInfo);
			}
			// 设置默认的商务核查人
			$.setAuditor(CurrentUser.get().getUsername());
		} else {

			if (task != null) {
				String businessKey = task.getBusinessKey();
				companyId = businessKey.split(":")[1];
			}
			$ = new CompanyInfoView();
			CompanyInfo one = companyInfoService.findOne(Long.parseLong(companyId));
			BeanUtils.copyProperties(one, $);
			List<QualificationInfo> all = qualificationInfoService.findAllByCompanyId(Long.parseLong(companyId));
			all.sort(new Comparator<QualificationInfo>() {
				@Override
				public int compare(QualificationInfo o1, QualificationInfo o2) {
					return o1.getAttachmentType() > o2.getAttachmentType() ? 1 : -1;
				}
			});
			qualificationInfoList = new ArrayList<>();
			for (int i = 1; i <= 6; i++) {
				QualificationInfo qualificationInfo = new QualificationInfo();
				qualificationInfo.setAttachmentType(i);
				qualificationInfoList.add(qualificationInfo);
			}
			for (int i = 0; i < all.size(); i++) {
				QualificationInfo qualificationInfo = all.get(i);
				Integer attachmentType = qualificationInfo.getAttachmentType();
				qualificationInfoList.set(attachmentType - 1, qualificationInfo);
			}
			productLinkInfoList = productLinkInfoService.findAllByCompanyId(Long.parseLong(companyId));
			productLinkInfoList.add(new ProductLinkInfo());

		}
		// 公司负责人
		principalList = systemUserService.findAll();
		// 商务核查人
		auditorList = workflowManagerService.findFirstActivitySystemUserProcDefKey(PROCESS_DEF_KEY);

	}

	/**
	 * 创建甲方公司的保存方法
	 */
	public void onCompanyInfoSave() {
		// 判断保存的公司名称是否存在
		if (StringUtils.isNotBlank($.getCompanyName())) {

			CompanyInfo dbCompanyInfo = companyInfoService.findCompanyInfoByCompanyName($.getCompanyName());

			if (dbCompanyInfo != null && ($.getId() == null || ($.getId() != null && $.getId() != dbCompanyInfo.getId()))) {
				addErrorMessage("公司已经存在！");
				return;
			}
		}
		$.setAuditStatus(AuditStatus.NO_SUBMIT.getIndex());
		companyInfoService.saveCompanyInfo($, qualificationInfoList, productLinkInfoList);
		addInfoMessage("保存成功");
	}

	public void onCompanyInfoSubmit() {
		// 判空验证
		try {
			checkBaseMessage($);
			checkQualificationInfoList($, qualificationInfoList);
		} catch (Exception e) {
			addErrorMessage(e.getMessage());
			return;
		}
		// 判断保存的公司名称是否存在
		String companyName = $.getCompanyName();
		if ($.getId() == null) {
			if (companyInfoService.findCompanyInfoByCompanyName(companyName) != null) {
				addErrorMessage("公司已经存在！");
				return;
			}
		}
		$.setAuditStatus(AuditStatus.NO_SUBMIT.getIndex());// 未提交状态
		companyInfoService.saveCompanyInfo($, qualificationInfoList, productLinkInfoList);

		Long companyId = $.getId();
		String account = CurrentUser.get().getUsername();
		String title = "【" + companyName + "】甲方审核";
		List businessKeys = Lists.newArrayList();
		businessKeys.add(companyId + "");
		Map<String, Object> variables = Maps.newHashMap();
		// variables.put("checker", $.getAuditor());
		// 启动工作流
		workflowProcessorService.startProcess(account, $.getAuditor(), PROCESS_DEF_KEY, title, businessKeys, variables);

		$.setAuditStatus(AuditStatus.NO_CHECK.getIndex());
		CompanyInfo companyInfo = companyInfoService.findOne(companyId);
		companyInfo.setAuditStatus(AuditStatus.NO_CHECK.getIndex());// 待复查状态
		companyInfoService.saveOrUpdate(companyInfo);
		addInfoMessage("提交成功");
	}

	public void onUploadBusinessLicense(FileUploadEvent event) throws Exception {
		QualificationInfo qualificationInfo = qualificationInfoList.get(0);
		qualificationInfo.setAttachmentUrl(this.uploadImg(event.getFile()));
		qualificationInfo.setUploadTime(new Date());
		qualificationInfo.setUploader(CurrentUser.get().getName());
		addInfoMessage("上传成功");
	}

	public void onUploadIdCard(FileUploadEvent event) {
		QualificationInfo qualificationInfo = qualificationInfoList.get(1);
		qualificationInfo.setAttachmentUrl(this.uploadImg(event.getFile()));
		qualificationInfo.setUploadTime(new Date());
		qualificationInfo.setUploader(CurrentUser.get().getName());
		addInfoMessage("上传成功");
	}

	public void onUploadLoanApproval(FileUploadEvent event) {
		QualificationInfo qualificationInfo = qualificationInfoList.get(2);
		qualificationInfo.setAttachmentUrl(this.uploadImg(event.getFile()));
		qualificationInfo.setUploadTime(new Date());
		qualificationInfo.setUploader(CurrentUser.get().getName());
		addInfoMessage("上传成功");
	}

	public void onUploadProductLogo(FileUploadEvent event) {
		QualificationInfo qualificationInfo = qualificationInfoList.get(3);
		qualificationInfo.setAttachmentUrl(this.uploadImg(event.getFile()));
		qualificationInfo.setUploadTime(new Date());
		qualificationInfo.setUploader(CurrentUser.get().getName());
		addInfoMessage("上传成功");
	}

	public void onUploadContract(FileUploadEvent event) {
		QualificationInfo qualificationInfo = qualificationInfoList.get(4);
		qualificationInfo.setAttachmentUrl(this.uploadImg(event.getFile()));
		qualificationInfo.setUploadTime(new Date());
		qualificationInfo.setUploader(CurrentUser.get().getName());
		addInfoMessage("上传成功");
	}

	public void onUploadTaxpayerQualification(FileUploadEvent event) {
		QualificationInfo qualificationInfo = qualificationInfoList.get(5);
		qualificationInfo.setAttachmentUrl(this.uploadImg(event.getFile()));
		qualificationInfo.setUploadTime(new Date());
		qualificationInfo.setUploader(CurrentUser.get().getName());
		addInfoMessage("上传成功");
	}

	// 删除删除的图片
	public void deleteImg(Integer flag) {
		QualificationInfo qualificationInfo = null;
		switch (flag) {
		case 1:
			qualificationInfo = qualificationInfoList.get(0);
			qualificationInfo.setUploader(null);
			qualificationInfo.setAttachmentUrl(null);
			qualificationInfo.setUploadTime(null);
			break;
		case 2:
			qualificationInfo = qualificationInfoList.get(1);
			qualificationInfo.setUploader(null);
			qualificationInfo.setAttachmentUrl(null);
			qualificationInfo.setUploadTime(null);
			break;
		case 3:
			qualificationInfo = qualificationInfoList.get(2);
			qualificationInfo.setUploader(null);
			qualificationInfo.setAttachmentUrl(null);
			qualificationInfo.setUploadTime(null);
			break;
		case 4:
			qualificationInfo = qualificationInfoList.get(3);
			qualificationInfo.setUploader(null);
			qualificationInfo.setAttachmentUrl(null);
			qualificationInfo.setUploadTime(null);
			break;
		case 5:
			qualificationInfo = qualificationInfoList.get(4);
			qualificationInfo.setUploader(null);
			qualificationInfo.setAttachmentUrl(null);
			qualificationInfo.setUploadTime(null);
			break;
		case 6:
			qualificationInfo = qualificationInfoList.get(5);
			qualificationInfo.setUploader(null);
			qualificationInfo.setAttachmentUrl(null);
			qualificationInfo.setUploadTime(null);
			break;
		}
	}

	// 添加产品链接
	public void addProductLink() {
		if (StringUtils.isNotBlank(productLink)) {
			ProductLinkInfo productLinkInfo = productLinkInfoList.get(productLinkInfoList.size() - 1);
			productLinkInfo.setProductLink(productLink);
			productLinkInfo.setRemark(remark);
			productLinkInfoList.add(new ProductLinkInfo());
			remark = null;
			productLink = null;
		}
	}

	// 改变合作模式
	public void onChangeCopMode() {
		$.setSettlementPriceCpa(null);
		$.setSettlementPriceCps(null);
	}

	// 改变是否是为一般纳税人
	public void onChangeGeneralTaxpayer() {
		QualificationInfo qualificationInfo = qualificationInfoList.get(5);
		qualificationInfo.setUploader(null);
		qualificationInfo.setAttachmentUrl(null);
		qualificationInfo.setUploadTime(null);
	}

	// 改变我司收款账户
	public void onChangeReceiveAccount() {
		String receivableAccount = $.getReceivableAccount();
		Map<String, List<Dictionary>> dictionaries = getDictionaries();
		List<Dictionary> dictionaryList = dictionaries.get(SETTLEMENT_RECEIVE_ACCOUNT);
		dictionaryList.forEach(dic -> {
			String account = dic.getValue1();
			if (account.equals(receivableAccount)) {
				$.setReceivableCardNumber(dic.getValue2());
			}
		});
	}

	// 改变我司收款账号
	public void onChangeReceiveAccountNumber() {
		String receivableCardNumber = $.getReceivableCardNumber();
		Map<String, List<Dictionary>> dictionaries = getDictionaries();
		List<Dictionary> dictionaryList = dictionaries.get(SETTLEMENT_RECEIVE_ACCOUNT);
		dictionaryList.forEach(dic -> {
			String accountNumber = dic.getValue2();
			if (accountNumber.equals(receivableCardNumber)) {
				$.setReceivableAccount(dic.getValue1());
			}
		});
	}

	// 是否开发票
	public void onChangeIfInvoice() {
		if ($.getIfInvoice() == false) {
			$.setInvoiceContent(null);
			$.setFirstPartyBank(null);
			$.setFirstPartyAccount(null);
			$.setFirstPartyCardNumber(null);
			$.setInvoiceAddress(null);
			$.setRecipientsName(null);
			$.setRecipientsMobile(null);
			$.setDeliveryAddress(null);

		} else {
			$.setPayer(null);
		}
	}

	// 改变结算周期
	public void onChangeSettlementPeroid() {
		$.setAmountAdvanced(null);
	}

	public static void checkBaseMessage(CompanyInfoView view) throws Exception {
		// 公司信息
		if (StringUtils.isBlank(view.getCompanyName())) {
			throw new SystemException("公司信息[公司名称不能为空]");
		}
		/*if (StringUtils.isBlank(view.getProductName())) {
			throw new SystemException("公司信息[产品名称不能为空]");
		}*/
		if (view.getCopMode() == null) {
			throw new SystemException("公司信息[合作模式不能为空]");
		}
		if (StringUtils.isBlank(view.getTaxIdentificationNumber())) {
			throw new SystemException("公司信息[纳税识别号不能为空]");
		}
		if (view.getCompanyBackground() == null) {
			throw new SystemException("公司信息[公司背景不能为空]");
		}
		if (StringUtils.isBlank(view.getContactName())) {
			throw new SystemException("公司信息[甲方商务姓名不能为空]");
		}
		if (StringUtils.isBlank(view.getContactPhone())) {
			throw new SystemException("公司信息[甲方商务电话不能为空]");
		}
		if (StringUtils.isBlank(view.getContactEmail())) {
			throw new SystemException("公司信息[甲方商务邮箱不能为空]");
		}
		if (StringUtils.isBlank(view.getFirstPartyAddress())) {
			throw new SystemException("公司信息[甲方实际办公地址不能为空]");
		}
		if (view.getVerifyMode() == null) {
			throw new SystemException("公司信息[甲方审核方式不能为空]");
		}
		if (StringUtils.isBlank(view.getPrincipal())) {
			throw new SystemException("公司信息[我司商务负责人不能为空]");
		}
		if (StringUtils.isBlank(view.getAuditor())) {
			throw new SystemException("公司信息[我司甲方商务核查人]");
		}

		// 结算信息验证
		// cpa 、cpc 合作模式
		if (view.getCopMode() == 0 || view.getCopMode() == 2) {
			if (view.getSettlementPriceCpa() == null) {
				throw new SystemException("结算信息[结算价格（元）不能为空]");
			}
		}
		// cps合作模式
		else if (view.getCopMode() == 1) {
			if (view.getSettlementPriceCps() == null) {
				throw new SystemException("结算信息[结算价格（%）不能为空]");
			}
		}
		// cpa+cps合作模式
		else if (view.getCopMode() == 3) {
			if (view.getSettlementPriceCpa() == null || view.getSettlementPriceCps() == null) {
				throw new SystemException("结算信息[结算价格不能为空]");
			}
		}

		if (view.getSettlementPeroid() == null) {
			throw new SystemException("结算信息[结算周期不能为空]");
		}
		if (view.getSettlementPaymentPeroid() == null) {
			throw new SystemException("结算信息[结算账期不能为空]");
		}
		// 结算周期选择为预付
		if (view.getSettlementPeroid() == 4) {
			if (view.getAmountAdvanced() == null) {
				throw new SystemException("结算信息[预付金额不能为空]");
			}
		}
		if (StringUtils.isBlank(view.getReceivableAccount())) {
			throw new SystemException("结算信息[我司收款账户不能为空]");
		}
		if (StringUtils.isBlank(view.getReceivableCardNumber())) {
			throw new SystemException("结算信息[我司收款卡号不能为空]");
		}
		// 开票信息验证
		if (view.getIfInvoice() == false) {
			if (StringUtils.isBlank(view.getPayer())) {
				throw new SystemException("开票信息[打款人姓名不能为空]");
			}
		} else {
			if (view.getInvoiceContent() == null) {
				throw new SystemException("开票信息[开票内容不能为空]");
			}
			if (StringUtils.isBlank(view.getFirstPartyBank())) {
				throw new SystemException("开票信息[甲方支行不能为空]");
			}
			if (StringUtils.isBlank(view.getFirstPartyAccount())) {
				throw new SystemException("开票信息[甲方银行账户不能为空]");
			}
			if (StringUtils.isBlank(view.getFirstPartyCardNumber())) {
				throw new SystemException("开票信息[甲方银行卡号不能为空]");
			}
			if (StringUtils.isBlank(view.getInvoiceAddress())) {
				throw new SystemException("开票信息[开票地址不能为空]");
			}
			if (StringUtils.isBlank(view.getRecipientsName())) {
				throw new SystemException("开票信息[收件人姓名不能为空]");
			}
			if (StringUtils.isBlank(view.getRecipientsMobile())) {
				throw new SystemException("开票信息[收件人手机号不能为空]");
			}
			if (StringUtils.isBlank(view.getDeliveryAddress())) {
				throw new SystemException("开票信息[收件详细地址不能为空]");
			}
		}

	}

	public static void checkQualificationInfoList(CompanyInfoView view, List<QualificationInfo> qualificationInfoList) throws Exception {
		QualificationInfo businessLicense = qualificationInfoList.get(0);
		if (businessLicense.getAttachmentUrl() == null) {
			throw new SystemException("营业执照没有上传", null);
		}
		if (view.getIfGeneralTaxpayer()) {
			QualificationInfo taxpayerQualification = qualificationInfoList.get(5);
			if (taxpayerQualification.getAttachmentUrl() == null) {
				//throw new SystemException("一般纳税人资质没有上传");
			}
		}

	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(SETTLEMENT_CYCLE, APPROVAL_TYPE, COOPERATION_MODE, COMPANY_BACKGROUND, SETTLEMENT_BILLING_CONTENT, SETTLEMENT_RECEIVE_ACCOUNT);
	}
}
